package wechat

import (
	myHttp "xianzhi/utils/http"
	myRedis "xianzhi/utils/redis"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/go-redis/redis"
	"time"
)

type AccessTokenRes struct {
	Errcode     int    `json:"errcode"`
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
	Errmsg      string `json:"errmsg"`
}

// 获取全局access_token
func GetAccessToken(key string) string {
	client, err := myRedis.GetClient()
	if err != nil {
		logs.Error("can not connect redis:", err)
		return ""
	}
	redisKey := key + "_access_token"
	accessToken, err := client.Get(redisKey).Result()
	if err == redis.Nil || err != nil {
		appId := beego.AppConfig.String("wechatappid")
		appSecret := beego.AppConfig.String("wechatappsecret")
		url := fmt.Sprintf(
			"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
			appId, appSecret)
		res, err := myHttp.GetData(url)
		if err != nil {
			logs.Error("request access token fail:", err)
			return ""
		}
		var data AccessTokenRes
		if err := json.Unmarshal([]byte(res), &data); err != nil {
			logs.Error("unmarshal access token response fail:", err)
			return ""
		}
		if data.Errcode != 0 {
			logs.Error("request access token fail:", data.Errmsg)
			return ""
		}
		accessToken = data.AccessToken
		client.Set(redisKey, accessToken, 6500*time.Second)
	}
	return accessToken
}
